<template>
  <div class="main-box">
    <uiTestCaseCat></uiTestCaseCat>

    <div class="table-box">
      <Table
          ref="table"
          :searchColumns="searchColumns"
          description_keywords="uiTestManage"
          @getTableList="getTableList"
          :toolButton='["refresh", "downloadIDE", "search", "description"]'
      >
        <template #tableHeader="scope">
          <el-button type="primary" :icon="CirclePlus" @click="showProjectFrom('create')">新增录制文件</el-button>
          <!--        <el-button  type="primary" :icon="Upload" plain @click="">批量添加菜单</el-button>-->
          <!--        <el-button  type="primary" :icon="Download" plain @click="">导出菜单数据</el-button>-->
          <!--        <el-button type="primary" plain @click="">To 子集详情页面</el-button>-->
          <!--        <el-button type="danger" :icon="Delete" plain  @click="">-->
          <!--          批量删除菜单-->
          <!--        </el-button>-->
        </template>
        <template #table>
          <!-- 表格主体 -->
          <el-table :data="tableList"
                    row-key="id"
                    border

                    style="width: 100%">
            <el-table-column prop="case_name" fixed="left" align="center" label="用例名称" width="200"/>
            <el-table-column prop="case_description" align="center" label="用例描述" min-width="300">
              <template #default="scope">
                <el-text line-clamp="3">
                  {{scope.row.case_description}}
                </el-text>
              </template>
            </el-table-column>
            <el-table-column align="center"  label="执行状态" width="100">
              <template #default="scope">
                <el-tag :type="getCaseRunType(scope.row.run_status)">{{scope.row.run_status_display}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="create_time" align="center" label="创建时间" width="170"/>
            <el-table-column prop="update_time" align="center" label="最近修改时间" width="170"/>
            <el-table-column align="center" fixed="right" label="操作" width="300">
              <template #default="scope">

                <el-dropdown split-button size="small"
                             type="primary" @click="runUiTest(scope)">
                  谷歌浏览器运行
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item>谷歌</el-dropdown-item>
                      <el-dropdown-item>火狐</el-dropdown-item>
                      <el-dropdown-item>EDGE</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <el-button
                    @click="showProjectFrom('update',scope)"
                    style="margin-left: 12px"
                    size="small">编辑

                </el-button>
                <el-button
                    size="small"
                    @click=""
                    type="danger">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </Table>
    </div>


    <el-dialog v-model="uiCaseFormDialogVisible"
               append-to-body
               :title="uiCaseFormDialogTitle" width="800" draggable>

      <el-form ref="uiCaseFormRef" :model="uiCaseFormData" :rules="uiCaseRules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用例名称:" prop="case_name">
              <el-input style="width: 100%;"
                        v-model="uiCaseFormData.case_name"
                        placeholder=请输入项目名称>
              </el-input>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="用例文件:" prop="case_url">
              <el-upload
                  class="case-file-uploader"
                  action="#"
                  ref="caseFileUpload"
                  :limit="1"
                  :on-exceed="handleExceed"
                  :auto-upload="true"
                  :show-file-list="true"
                  :http-request="uploadSectionFile"
                  :before-upload="beforeUiCaseUpload"
                  :on-change="beforeUiCaseUpload"
                  :on-remove="handleRemove"
              >
                <template #trigger>
                  <el-button type="primary">选择文件</el-button>
                </template>
                <!--                <img v-if="projectFormData.project_icon" :src="baseURL + projectFormData.project_icon" alt=""-->
                <!--                     class="pic-img"/>-->
                <!--                <el-icon v-else class="pic-uploader-icon">-->
                <!--                  <Plus/>-->
                <!--                </el-icon>-->
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="用例描述:">
              <el-input style="width: 100%;"
                        v-model.trim="uiCaseFormData.case_description"
                        type="textarea"
                        rows="5"
                        placeholder=请输入项目描述>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="">取消</el-button>
          <el-button type="primary" :loading="loading" @click="commitUiCaseFrom(uiCaseFormRef)">确定
          </el-button>
        </div>
      </template>

    </el-dialog>

  </div>


</template>

<script setup>

import uiTestCaseCat from "@/views/ui/uiTestManage/uiTestCat/index.vue";
import {CirclePlus, Plus} from "@element-plus/icons-vue";
import Table from "@/components/Table/index.vue";
import {onMounted, reactive, ref} from "vue";
import {ElMessage, genFileId} from "element-plus";
import {
  getUiTestCaseApi,
  getUiTestCaseListApi, postRunUiTestCase,
  postUiCaseFile,
  postUiTestCaseApi
} from "@/api/modules/ui/uitest.js";
import {useProjectStore} from "@/stores/modules/project/project.js";
import {storeToRefs} from "pinia";
import {useUiTestStore} from "@/stores/modules/ui/uitest.js";
// import {wsInstance} from "@/utils/wsMessage.js";

const uiTestStore = useUiTestStore()
const projectStore = useProjectStore()

const {currentProject, currentProjectId} = storeToRefs(projectStore)
const {
  uiTestCatTree,
  selectedUiTestCatName,
  selectedUiTestCatId,
} = storeToRefs(uiTestStore)


// 需要搜索的配置项
const searchColumns = ref([
  {label: "项目名称", field: "project_name", searchType: "input"},
])

const tableList = ref([])

onMounted(() => {
  getTableList()
})

const table = ref(null)
const searchArgsDict = ref({})
const getTableList = async (searchArgs) => {
  const {data} = await getUiTestCaseListApi(searchArgs)
  searchArgsDict.value = searchArgs
  tableList.value = data.data
  table.value.pageable.pageNum = data.page
  table.value.pageable.pageSize = data.pagesize
  table.value.pageable.total = data.total
}

const getCaseRunType = (run_status)=>{
  const status_type={
    1:"info",
    2:"primary",
    3:"warning",
    4:"success",
    5:"danger"
  }
  return status_type[run_status]
}


const uiCaseFormDialogVisible = ref(false)
const uiCaseFormDialogTitle = ref("")
const uiCaseFormData = ref({})
const showProjectFrom = (formType, scope = undefined) => {
  uiCaseFormDialogVisible.value = true

  if (formType === "create") {
    uiCaseFormDialogTitle.value = "新增录制文件"
  }
  if (formType === "update") {
    uiCaseFormDialogTitle.value = "编辑录制文件"
    let project_id = scope.row.id
    console.log(project_id)
    getUiTestCaseApi(project_id).then(res => {
      uiCaseFormData.value = res
    })
  }

}


const baseURL = import.meta.env.VITE_API_URL
const caseFileUpload = ref()
const handleExceed = (files) => {
  caseFileUpload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  caseFileUpload.value.handleStart(file)
}

const uploadSectionFile = (params) => {
  const file = params.file
  // 根据后台需求数据格式
  const form = new FormData();
  // 文件对象
  form.append("file", file);
  // form.append("Content-Type", 'multipart/form-data');
  console.log(file.size)
  // 上传头像的请求方法
  postUiCaseFile(form).then(res => {
    uiCaseFormData.value.case_url = res.data
  })
}


const beforeUiCaseUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('文件不能大于 10MB!')
    handleExceed(rawFile)
    return false
  }

  if (rawFile.name.split(".").pop().toLowerCase() !== "side") {
    ElMessage.error('请上传side格式的录制文件')
    // 清除文件
    handleExceed(rawFile)
    return false
  }
  return true
}

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}


const uiCaseFormRef = ref();
const uiCaseRules = reactive({
  case_name: [{required: true, message: "请输入用例名称", trigger: "blur"}],
  // case_url: [{required: true, message: "请上传文件"}],
});


const loading = ref(false);
const commitUiCaseFrom = (formEl, catId = undefined) => {
  // 提交时，上传文件
  // caseFileUpload.value.submit()

  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      if (uiCaseFormData.value.id) {
        console.log("编辑")
      } else {
        postUiTestCaseApi({
          ...uiCaseFormData.value,
          cat: catId ? catId : selectedUiTestCatId.value,
          project: currentProjectId.value
        }).then(res => {
          ElMessage.success("新增成功");
          uiCaseFormDialogVisible.value = false;
          getTableList(searchArgsDict.value);

        })
      }

    } finally {
      loading.value = false;
    }
  })
}

const cancel = () => {

}


const runUiTest = (scope, browserType = undefined) => {
  // $ws.send(JSON.stringify(
  //     {
  //       type: "runUiTest",
  //       data: {
  //         browser: browserType?browserType:"chrome",
  //         id: scope.row.id
  //       }
  //     }
  // ));

  let uiTestCase = {
            browser: browserType?browserType:"chrome",
            id: scope.row.id
          }

  postRunUiTestCase(uiTestCase).then(res=>{

  })

  ElMessage.success("已添加到运行队列中")

}


</script>

<style lang="scss">

.case-file-uploader {
  .el-button {
    width: 200px;
  }

  .el-upload-list {
    width: 200px;
  }
}


//.pic-uploader .el-upload {
//  border: 1px dashed var(--el-border-color);
//  border-radius: 50%;
//  cursor: pointer;
//  position: relative;
//  overflow: hidden;
//  transition: var(--el-transition-duration-fast);
//}
//
//.pic-uploader .el-upload:hover {
//  border-color: var(--el-color-primary);
//}
//
//.el-icon.pic-uploader-icon {
//  font-size: 28px;
//  color: #8c939d;
//  width: 50px;
//  height: 50px;
//  text-align: center;
//}

</style>
